package service.action;

import database.app.PersonDao;
import model.app.Person;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;

import static service.CustomProtocol.*;

/**
 * Created with IntelliJ IDEA.
 * Author: Kostika Gorica
 * User:   kosta
 * Date:   3/2/13
 * Time:   10:16 PM
 */
public class PersonServlet extends HttpServlet {


    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        long startTime=System.currentTimeMillis();
        PrintWriter out = response.getWriter();

        out.println(XML_VERSION);
        out.println(SERVICE_START);

        String actionTodo = request.getParameter("action");
        switch (actionTodo.toLowerCase()){
            case "addperson":
            {
                String pers = request.getParameter("person");

                if (pers==null){
                    out.println(STATUS_START);
                    out.println(BAD_REQUEST);
                    out.println(BAD_REQUEST_DEFAULT_MESSAGE);
                    out.println(STATUS_STOP);
                    out.println(SERVICE_STOP);
                    break;
                }

                Person person;
                try {

                    JAXBContext jc = JAXBContext.newInstance( Person.class );
                    Unmarshaller u = jc.createUnmarshaller();
                    StringBuffer xmlStr = new StringBuffer( "<?xml version=\"1.0\"?>").append(pers);
                    person = (Person) u.unmarshal( new StreamSource( new StringReader( xmlStr.toString())));
                } catch (JAXBException e) {
                    out.println(STATUS_START);
                    out.println(BAD_REQUEST);
                    out.println(BAD_REQUEST_DEFAULT_MESSAGE);
                    out.println(STATUS_STOP);
                    out.println(SERVICE_STOP);
                    e.printStackTrace();
                    break;
                }

                if (!person.isValid()){
                    out.println(STATUS_START);
                    out.println(BAD_REQUEST);
                    out.println(BAD_REQUEST_DEFAULT_MESSAGE);
                    out.println(STATUS_STOP);
                    out.println(SERVICE_STOP);
                    break;
                }
                person.setId(PersonDao.getNextPersonId());
                int rows = PersonDao.insertPerson(person);

                if (rows < 1 ){
                    out.println(STATUS_START);
                    out.println(SERVER_ERROR);
                    out.println(DEPARTMENT_FAILED_INSERT);
                    out.println(STATUS_STOP);
                    out.println(SERVICE_STOP);
                    break;
                }

                out.println(STATUS_START);
                out.println(STATUS_OK);
                out.println(REGISTRATION_SUCCESS);
                out.println(STATUS_STOP);
                out.println(SERVICE_STOP);
                break;
            }

            case "updateperson" :
            {
                String pers = request.getParameter("person");
                String id = request.getParameter("id");

                if (pers==null || id==null ||id.trim().length()!=15){
                    out.println(STATUS_START);
                    out.println(BAD_REQUEST);
                    out.println(BAD_REQUEST_DEFAULT_MESSAGE);
                    out.println(STATUS_STOP);
                    out.println(SERVICE_STOP);
                    break;
                }

                Person person;
                try {
                    JAXBContext jc = JAXBContext.newInstance( Person.class );
                    Unmarshaller u = jc.createUnmarshaller();
                    StringBuffer xmlStr = new StringBuffer( "<?xml version=\"1.0\"?>").append(pers);
                    person = (Person) u.unmarshal( new StreamSource( new StringReader( xmlStr.toString())));
                } catch (JAXBException e) {
                    out.println(STATUS_START);
                    out.println(BAD_REQUEST);
                    out.println(BAD_REQUEST_DEFAULT_MESSAGE);
                    out.println(STATUS_STOP);
                    out.println(SERVICE_STOP);
                    e.printStackTrace();
                    break;
                }

                if (!person.isValid()){
                    out.println(STATUS_START);
                    out.println(BAD_REQUEST);
                    out.println(BAD_REQUEST_DEFAULT_MESSAGE);
                    out.println(STATUS_STOP);
                    out.println(SERVICE_STOP);
                    break;
                }
                person.setId(id.trim());

                int rows = PersonDao.updatePerson(person);

                if (rows < 1 ){
                    out.println(STATUS_START);
                    out.println(SERVER_ERROR);
                    out.println(DEPARTMENT_FAILED_INSERT);
                    out.println(STATUS_STOP);
                    out.println(SERVICE_STOP);
                    break;
                }

                out.println(STATUS_START);
                out.println(STATUS_OK);
                out.println(REGISTRATION_SUCCESS);
                out.println(STATUS_STOP);
                out.println(SERVICE_STOP);
                break;
            }

            case "deleteperson" :
            {
                //TODO consider when has jobs
                String id = request.getParameter("id");
                if(id==null || id.trim().length()!=15){
                    out.println(STATUS_START);
                    out.println(BAD_REQUEST);
                    out.println(BAD_REQUEST_DEFAULT_MESSAGE);
                    out.println(STATUS_STOP);
                    out.println(SERVICE_STOP);
                    break;
                }
                Person person = PersonDao.getSinglePerson(id.trim());
                person.setStatus("NADEL");
                int row=PersonDao.updatePerson(person);
                if (row!=1){
                    out.println(STATUS_START);
                    out.println(SERVER_ERROR);
                    out.println(DELETE_FAILED);
                    out.println(STATUS_STOP);
                    out.println(SERVICE_STOP);
                    break;
                }
                out.println(STATUS_START);
                out.println(STATUS_OK);
                out.println(DELETE_SUCCESS);
                out.println(STATUS_STOP);
                out.println(SERVICE_STOP);
                break;
            }
            default:
            {
                out.println(STATUS_START);
                out.println(NOT_IMPLEMENTED);
                out.println(NOT_IMPLEMENTED_DEFAULT_MESSAGE);
                out.println(STATUS_STOP);
                out.println(SERVICE_STOP);
            }
        }
        System.out.println("Time job: " + actionTodo + ": " + (System.currentTimeMillis() - startTime));
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
